package com.fw.kafka_chapter_1.quick;

import com.fw.kafka_chapter_1.quick.interceptor.ConcumerInterceptorShould;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * @Author:yanwei
 * @Date: 2020/8/16 - 17:48
 *
 * Kafka 消息接受者
 */
@Slf4j
public class ConcumerStart {

    public static void main(String[] args) {
        Properties properties = new Properties();
        // key 序列化器指定
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // value 序列化执行
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        // 指定组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"fw_group");
        // 指定连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.227.129:9092");
        //指定拦截器
        properties.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, ConcumerInterceptorShould.class.getName());
        //创建接收器
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);
        // 指定 topic
        consumer.subscribe(Collections.singletonList("fw"));

        while (true){
            // 10 毫秒获取一次
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(10));
            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {
                System.err.println(stringStringConsumerRecord.value());
            }
        }
    }
}
